package com.dc.dbus.transport.netty.server;

import java.io.IOException;

import com.dc.dbus.transport.commons.ServerSideReceiver;
import com.dc.dbus.transport.netty.Log;
import com.dc.dbus.transport.netty.Msg;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.channel.SimpleChannelInboundHandler;

public class MainHandler extends SimpleChannelInboundHandler<Msg> {

	protected final ClientChannelCenter clientChannelCenter;
    
    protected final ServerSideReceiver serverSideReceiver;
    
	public MainHandler(ClientChannelCenter clientChannelCenter,
			ServerSideReceiver serverSideReceiver) {
		super();
		this.clientChannelCenter = clientChannelCenter;
		this.serverSideReceiver = serverSideReceiver;
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {

		// 客户端连接到服务

		Channel channel = ctx.channel();
		ChannelId channelId = channel.id();
		String address = channel.remoteAddress().toString();

		clientChannelCenter.clientActive(channelId, channel, address);

		super.channelActive(ctx);
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {

		// 客户端断开连接

		Channel channel = ctx.channel();
		ChannelId channelId = channel.id();
		String address = channel.remoteAddress().toString();

		clientChannelCenter.clientDisconnect(channelId, channel, address);
		
	}
	
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, Msg msg) throws Exception {
		
		//接收到客户端消息
		
		Channel channel = ctx.channel();
//		ChannelId channelId = channel.id();
		String address = channel.remoteAddress().toString();
    	
		serverSideReceiver.handlerMsg(address, msg.msgId, msg.cmd, msg.param);
	}

	@Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
    	
    	//异常处理
    	
    	if( cause instanceof IOException ) {
    		
    		IOException e = (IOException)cause;
    		
    		//如果是客户端断线事件，则捕获
    		if( e.getMessage().equals("远程主机强迫关闭了一个现有的连接。") ) {

				Log.nettyLinkLogger.error("Connection Lost(IOException): " + ctx.channel().remoteAddress().toString());
    			
    		} else {
    			
    			//不是客户端断线则抛出继续抛出异常
    			super.exceptionCaught(ctx, cause);;
    		}
    		
    	} else {
    		
    		//不是客户端断线则抛出继续抛出异常
    		super.exceptionCaught(ctx, cause);;
    	}
    	
    }
}
